package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.ContactVo;
import com.tanhua.domain.vo.MessageLike;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IMService {

    @Autowired
    private HuanXinTemplate template;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private FriendApi friendApi;

    @Reference
    private CommentApi commentApi;

    /**
     * 回复陌生人消息
     *   * 向环信通信发送一条信息
     */
    public ResponseEntity replyQuestions(Long userId, String reply) {
        UserInfo info = userInfoApi.findById(UserHolder.getUserId());
        Question question = questionApi.findByUserId(userId);

        //1、组装信息内容
        Map<String, Object> map = new HashMap<>();
        map.put("userId", info.getId().toString());
        map.put("nickname", info.getNickname());
        map.put("strangerQuestion", question==null?"黑马36怎么样？":question.getTxt());
        map.put("reply", reply);

        String msg = JSON.toJSONString(map);
        //2、调用template发送消息
        template.sendMsg(userId.toString(),msg); //目标用户id，消息内容
        //3、构造返回值
        return ResponseEntity.ok(null);
    }

    /**
     * 添加好友
     */
    public ResponseEntity contactUser(Long friendId) {
        //1、保存好友关系
        friendApi.save(UserHolder.getUserId(),friendId);
        //2、将好友关系注册到环信系统
        template.contactUsers(UserHolder.getUserId(),friendId);
        return ResponseEntity.ok(null);
    }

    //分页查询联系人列表
    public ResponseEntity<PageResult> queryContactsList(Integer page, Integer pagesize, String keyword) {
        //1、调用API 查询当前用户的好友列表  PageResult<Friend>
        PageResult result = friendApi.findAll(page,pagesize,keyword,UserHolder.getUserId());
        //2、获取数据列表
        List<Friend> items = (List<Friend>) result.getItems();
        //3、循环列表，构造vo
        List<ContactVo> list  = new ArrayList<>();
        for (Friend item : items) {
            UserInfo userInfo = userInfoApi.findById(item.getFriendId());
            ContactVo vo = new ContactVo();
            BeanUtils.copyProperties(userInfo, vo);
            vo.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
            vo.setUserId(userInfo.getId().toString());
            list.add(vo);
        }
        result.setItems(list);
        //4、构建返回值
        return ResponseEntity.ok(result);
    }

    //查询被点赞列表
    public ResponseEntity<PageResult> messageList(Integer page, Integer pagesize, int commentType) {
        //1、获取当前操作用户（被点赞，评论，喜欢）
        Long userId = UserHolder.getUserId();
        //2、调用API查询 PageResult<Comment>
        PageResult result = commentApi.messageList(page,pagesize,commentType,userId);
        //3、构造返回值
        List<Comment> items = (List<Comment>) result.getItems();
        List<MessageLike> list = new ArrayList<>();
        for (Comment item : items) {
            MessageLike vo = new MessageLike();
            UserInfo info = userInfoApi.findById(item.getUserId());
            BeanUtils.copyProperties(info, vo);
            vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(item.getCreated())));
            list.add(vo);
        }
        result.setItems(list);
        return ResponseEntity.ok(result);
    }
}
